<template>
    <div class="user-list defaultBg">
        <div v-loading="loading" v-if="loading" class="loading"></div>
        <my-table
            :tableColumns="tableColumns"
            :isInline="true"
            :tableList="userList"
            :searchData="searchData"
            :searchButtonList="searchButtonList"
            :tableButtonList="tableButtonList"
            :count="userCount"
            @sizeChange="sizeChange"
            @pageChange="pageChange">
        </my-table>

        <!-- 更改密码弹窗 -->
        <el-dialog title="更改密码" :visible.sync="pwdDialogVisible" width="30%" :beforeClose="pwdFormCancel">
            <el-form :model="pwdForm" :rules="pwdrules" ref="pwdForm">
                <el-form-item label="请输入密码" prop="password" :label-width="formLabelWidth">
                    <el-input v-model="pwdForm.password" type="password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="请再次输入密码" prop="passwordAgain" :label-width="formLabelWidth">
                    <el-input v-model="pwdForm.passwordAgain" type="password" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="pwdFormCancel">取 消</el-button>
                <el-button type="primary" @click="pwdFormPost">更 改</el-button>
            </div>
        </el-dialog>

        <!-- 编辑用户信息弹窗 -->
        <el-dialog title="编辑用户信息" :visible.sync="editUserDialogVisible" width="30%">
            <!-- 头像上传 -->
            <div class="avatar-container">
                <el-upload
                    class="avatar-uploader"
                    :action="avatarUnloadURL"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :headers="headers"
                    name='avatar'
                    :data="avatarParameter">
                    <img v-if="avatarUrl" :src="avatarUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </div>

            <!-- 编辑表单 -->
            <el-form :model="editUserForm" :rules="editUserRules" ref="editUserForm">
                <el-form-item label="用户账号" prop="userAccount" :label-width="formLabelWidth">
                    <el-input v-model="editUserForm.userAccount" disabled autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户名称" prop="userName" :label-width="formLabelWidth">
                    <el-input v-model="editUserForm.userName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户电话" prop="userTel" :label-width="formLabelWidth">
                    <el-input v-model="editUserForm.userTel" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户角色" prop="role" :label-width="formLabelWidth">
                    <el-select v-model="editUserForm.role" placeholder="请选择角色">
                        <el-option
                            v-for="item in userRoleOptions"
                            :key="item.id"
                            :label="item.roleName"
                            :value="item.roleCode">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editUserFormCancel">取 消</el-button>
                <el-button type="primary" @click="editUserFormPost">更 改</el-button>
            </div>
        </el-dialog>

        <!-- 新增用户表单 -->
        <el-dialog title="新增用户" :visible.sync="addUserDialogVisible" width="30%" :beforeClose="addUserFormCancel">
            <!-- 新增表单 -->
            <el-form :model="addUserForm" :rules="addUserRules" ref="addUserForm">
                <el-form-item label="用户账号" prop="userAccount" :label-width="formLabelWidth">
                    <el-input v-model="addUserForm.userAccount" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户名称" prop="userName" :label-width="formLabelWidth">
                    <el-input v-model="addUserForm.userName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户电话" prop="userTel" :label-width="formLabelWidth">
                    <el-input v-model="addUserForm.userTel" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户角色" prop="role" :label-width="formLabelWidth">
                    <el-select v-model="addUserForm.role" placeholder="请选择角色">
                        <el-option
                            v-for="item in userRoleOptions"
                            :key="item.id"
                            :label="item.roleName"
                            :value="item.roleCode">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="密码" prop="password" :label-width="formLabelWidth">
                    <el-input type="password" v-model="addUserForm.password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="再次输入密码" prop="passwordAgain" :label-width="formLabelWidth">
                    <el-input type="password" v-model="addUserForm.passwordAgain" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addUserFormCancel">取 消</el-button>
                <el-button type="primary" @click="addUserFormPost">提 交</el-button>
            </div>
        </el-dialog>

        <el-dialog title="批量上传" :visible.sync="batchUploadFlag" width="40%">
            <div class="batch-contant">
                <batch-upload @batchList="batchListEmit"></batch-upload>
            </div>
        </el-dialog>

        <el-dialog title="批量注册学生账号" :visible.sync="batchUploadListFlag" width="42%">
            <Mtable v-if="isShowBatchTable" :tableColumns="batchLoginColumns" :isInline="true" :tableList="batchLoginList"
                :count="1000" :isPagination="false" :isButton="false" :tableHeight="400">
            </Mtable>
            <div slot="footer" class="dialog-footer">
                <el-button @click="batchLoginCancel">取 消</el-button>
                <el-button type="primary" @click="batchLogin">提 交</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { getUserList, deleteUser, modefiyActiveStatus, modefiyPwd, modifyUserInfo, addUser, batchRegister } from '@/api/user'
import { getRoleList } from '@/api/role'
import BatchUpload from '@/components/BatchUpload/BatchUpload.vue'
import Mtable from '@/components/MTable/MTable.vue'
export default {
    name: 'user-list',
    components: {
        BatchUpload,
        Mtable
    },
    computed: {
        ...mapGetters([
            'name',
            'roleCode'
        ]),
    },
    data () {
        // 密码验证
        var pwdFormvalidatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'))
            } else if (value.length < 6) {
                callback(new Error('密码长度不小于6'))
            }
            else {
                if (this.pwdForm.passwordAgain !== '') {
                    this.$refs.pwdForm.validateField('passwordAgain')
                }
                callback()
            }
        }
        var addFormvalidatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'))
            } else if (value.length < 6) {
                callback(new Error('密码长度不小于6'))
            }
            else {
                if (this.addUserForm.passwordAgain !== '') {
                    this.$refs.addUserForm.validateField('passwordAgain')
                }
                callback()
            }
        }
        // 密码验证
        var addFormvalidatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.addUserForm.password) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }
        var pwdFormvalidatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.pwdForm.password) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }
        // 电话号码验证
        var validateUserTel = (rule, value, callback, form) => {
            const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
            if (value.length == 11) {
                if (!reg.test(value)) {
                    callback(new Error('请输入正确格式的电话号码'))
                } else {
                    callback()
                }
            } else {
                callback(new Error('请输入11位电话号码'))
            }
        }

        return {
            // 搜索框的数据
            searchData: [
                { type: 'text', name: 'userAccount', label: '账号', value: '' },
                { type: 'select', name: 'isActive', label: '激活状态', value: '', options: [{ id: 0, text: '已冻结' }, { id: 1, text: '已激活' }] },
                { type: 'text', name: 'userName', label: '姓名', value: '' },
                // { type: 'text', name: 'role', label: '角色', value: '' },
                { type: 'text', name: 'userTel', label: '电话', value: '' },
            ],
            // 搜索按钮数据
            searchButtonList: [
                {
                    id: 'search',
                    name: '查询',
                    type: 'primary',  // primary/warning/danger/success
                    icon: 'el-icon-search',
                    size: 'small',
                    click: (btnList, that) => {
                        // this 当前vue页面
                        // btnList 当前的 searchButtonList数组
                        // that mForm表单页面的this
                        this.getList(that.mform)
                    }
                },
                {
                    id: 'reset',
                    name: '重置',
                    type: '',  // primary/warning/danger/success
                    icon: 'el-icon-refresh-right',
                    size: 'small',
                    click: (btnList, that, parent) => {
                        // this 当前vue页面
                        // btnList 当前的 searchButtonList数组
                        // that mForm表单页面的this
                        this.getList()
                        that.$refs.mform.resetFields()
                    }
                }
            ],
            // 表格头
            tableColumns: [
                { name: 'userName', label: '姓名', width: '200' },
                { name: 'userAccount', label: '账号', width: '200' },
                { name: 'roleName', label: '角色', width: '200' },
                { name: 'userTel', label: '电话号码', width: '220' },
                {
                    name: 'isActive', label: '激活状态', align: 'center', width: '100',
                    /**
                     * @param {Object} h 渲染函数参数对象
                     * @param {Number} index 该行下角标
                     * @param {Object} row 所在行对象
                     * @param {Object} column 所在列对象
                     * @param {Object} scope 表格项对象
                    */
                    render: (h, index, row, column, scope) => {
                        return (
                            <span>
                                <el-switch
                                    value={row.isActive}
                                    active-value={true}
                                    inactive-value={false}
                                    disabled={row.userName === this.name || (this.roleCode !== 'super_admin' && this.roleCode !== 'admin')}
                                    onChange={async () => {
                                        // 激活状态取反 // 发送请求
                                        row.isActive = await this.isActiveChangeFn(row.userAccount, row.isActive)
                                        console.log(row.isActive)
                                    }}
                                ></el-switch>
                            </span >
                        )
                    },
                },
                {
                    name: 'operation', label: '操作', align: "center",
                    /**
                     * @param {Object} h 渲染函数参数对象
                     * @param {Number} index 该行下角标
                     * @param {Object} row 所在行对象
                     * @param {Object} column 所在列对象
                     * @param {Object} scope 表格项对象
                    */
                    render: (h, index, row, column, scope) => {
                        return (
                            <span>
                                <el-button icon="el-icon-edit-outline" size="small" type="primary" disabled={(this.roleCode !== 'super_admin' && this.roleCode !== 'admin')} nativeOn-click={(e) => {
                                    // 打开用户编辑弹出框
                                    this.editUserDialogVisible = true
                                    this.editUserForm.userAccount = row.userAccount
                                    this.avatarParameter.userAccount = row.userAccount
                                    this.avatarUrl = process.env.VUE_APP_BASE_API + row.avatar
                                    this.editUserForm.userName = row.userName
                                    this.editUserForm.userTel = row.userTel
                                    this.editUserForm.role = row.role
                                    e.stopPropagation() // 阻止事件冒泡，避免表格行被选中
                                }}>编辑</el-button>

                                <el-button icon="el-icon-edit" size="small" type="warning" disabled={(this.roleCode !== 'super_admin' && this.roleCode !== 'admin')} nativeOn-click={(e) => {
                                    // 打开密码弹出框
                                    this.pwdDialogVisible = true
                                    this.pwdForm.userAccount = row.userAccount
                                    e.stopPropagation() // 阻止事件冒泡，避免表格行被选中
                                }}>更改密码</el-button>

                                <el-button icon="el-icon-delete" disabled={row.userName === this.name || (this.roleCode !== 'super_admin' && this.roleCode !== 'admin')} size="small" type="danger" nativeOn-click={(e) => {
                                    this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                                        confirmButtonText: '确定',
                                        cancelButtonText: '取消',
                                        type: 'warning'
                                    }).then(async () => {
                                        const res = await deleteUser(row.userAccount)
                                        if (res.hasOk) {
                                            this.$message({ message: res.message, type: 'warning' })
                                            this.getList()
                                        } else {
                                            this.$message({ message: res.message, type: 'error' })
                                        }
                                    }).catch(() => { })
                                    e.stopPropagation() // 阻止事件冒泡，避免表格行被选中
                                }}>删除</el-button>
                            </span>
                        )
                    },
                }
            ],
            // 表格按钮数据
            tableButtonList: [
                {
                    id: 'add',
                    name: '添加用户',
                    type: 'primary',  // primary/warning/danger/success
                    icon: 'el-icon-plus',
                    size: 'small',
                    click: (btnList, that) => {
                        // this 当前vue页面
                        // btnList 当前的 searchButtonList数组
                        // that mForm表单页面的this
                        this.addUserDialogVisible = true
                    }
                },
                {
                    id: 'batchAdd',
                    name: '批量注册',
                    type: 'primary',  // primary/warning/danger/success
                    icon: 'el-icon-upload2',
                    size: 'small',
                    click: (btnList, that) => {
                        // this 当前vue页面
                        // btnList 当前的 searchButtonList数组
                        // that mForm表单页面的this
                        this.batchUploadFlag = true
                    }
                }
            ],
            // 表格内容
            userList: [],
            // 数据是否准备完毕
            dataIsReady: false,


            formLabelWidth: '120px',

            // 更改密码弹窗
            pwdDialogVisible: false,
            pwdForm: {
                userAccount: '',
                password: '',
                passwordAgain: ''
            },
            pwdrules: {
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { validator: pwdFormvalidatePass, trigger: 'blur' }
                ],
                passwordAgain: [
                    { required: true, message: '请再次输入密码', trigger: 'blur' },
                    { validator: pwdFormvalidatePass2, trigger: 'blur' }
                ],
            },

            // 编辑用户信息弹窗
            editUserDialogVisible: false,
            editUserForm: {
                userAccount: '',
                userName: '',
                userTel: '',
                role: ''
            },
            userRoleOptions: [], // 角色列表
            editUserRules: {
                userAccount: [
                    { required: true, message: '缺少用户账号', trigger: 'blur' }
                ],
                userName: [
                    { required: true, message: '请输入用户名称', trigger: 'blur' },
                    { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
                ],
                userTel: [
                    { required: true, message: '请输入电话号码', trigger: 'blur' },
                    { validator: validateUserTel, trigger: 'blur' }
                ],
                role: [
                    { required: true, message: '请选择用户角色', trigger: 'blur' },
                ]
            },

            // 头像上传
            avatarParameter: {
                userAccount: ''
            },
            // 请求头
            headers: {
                'X-Token': getToken()
            },
            avatarUnloadURL: process.env.VUE_APP_BASE_API + 'user/uploadAvatar',
            avatarUrl: '',

            // 新增用户弹窗配置
            addUserDialogVisible: false,
            addUserForm: {
                userAccount: '',
                userName: '',
                password: '',
                passwordAgain: '',
                userTel: '',
                role: ''
            },
            addUserRules: {
                userAccount: [
                    { required: true, message: '缺少用户账号', trigger: 'blur' }
                ],
                userName: [
                    { required: true, message: '请输入用户名称', trigger: 'blur' },
                    { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
                ],
                userTel: [
                    { required: true, message: '请输入电话号码', trigger: 'blur' },
                    { validator: validateUserTel, trigger: 'blur' }
                ],
                role: [
                    { required: true, message: '请选择用户角色', trigger: 'blur' },
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { validator: addFormvalidatePass, trigger: 'blur' }
                ],
                passwordAgain: [
                    { required: true, message: '请再次输入密码', trigger: 'blur' },
                    { validator: addFormvalidatePass2, trigger: 'blur' }
                ],
            },
            // 列表数据是否准备完
            loading: true,
            // 当前页码
            offect: 1,
            // 当前列表显示条数
            limit: 10,
            // 表格长度
            userCount: 0,

            // 批量上传弹窗
            batchUploadFlag: false,
            batchUploadListFlag: false,
            isShowBatchTable: false,
            batchLoginList: [],
            batchLoginColumns: [
                { name: 'userAccount', label: '账号', width: '200' },
                { name: 'userName', label: '姓名', width: '200' },
                { name: 'password', label: '密码', width: '200' },
            ]
        }
    },
    watch: {
        roleCode: {
            handler (val, oldVal) {
                if (val !== 'super_admin' && val !== 'admin') {
                    this.tableButtonList = []
                } else {

                }
            },
            immediate: true
        }
    },
    methods: {
        // 获取用户列表
        async getList (searchData = {}) {
            searchData.limit = this.limit
            searchData.offect = this.offect
            const { data } = await getUserList(searchData)
            this.userList = data.resList
            this.userCount = data.count
            console.log(this.offect)
            this.dataIsReady = true
            this.loading = false
        },
        // 更改账号的激活状态
        async isActiveChangeFn (userAccount, isActive) {
            isActive = !isActive
            const res = await modefiyActiveStatus(userAccount, isActive)
            if (res.hasOk) {
                if (!res.data.isActive) {
                    this.$message({
                        message: '账号已冻结！',
                        type: 'warning'
                    })
                } else {
                    this.$message({
                        message: '账号已解冻！',
                        type: 'success'
                    })
                }
                // 返回执行完后的状态
                return res.data.isActive
            } else {
                this.$message({
                    message: res.message,
                    type: 'warning'
                })
                // 状态更改错误，返回原状态
                return !isActive
            }
        },

        // 取消更改密码
        pwdFormCancel () {
            // 重置输入框
            this.pwdDialogVisible = false
            this.$refs.pwdForm.resetFields()
        },
        // 更改密码提交
        pwdFormPost () {
            this.$refs.pwdForm.validate(async (valid) => {
                if (valid) {
                    // 提交编辑后的用户信息
                    const res = await modefiyPwd(this.pwdForm)
                    if (res.hasOk) {
                        this.$message({
                            message: '密码修改成功',
                            type: 'success'
                        })
                    } else {
                        this.$message({
                            message: res.message,
                            type: 'error'
                        })
                    }
                    // 重置表格
                    this.getList()
                    this.pwdDialogVisible = false
                    this.$refs.pwdForm.resetFields()
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },

        // 获取所有角色信息
        async getRoleList (searchData = {}) {
            searchData.limit = 100
            searchData.offect = 1
            const { data } = await getRoleList(searchData)
            this.userRoleOptions = data.resList
        },

        // 取消编辑用户
        editUserFormCancel () {
            // 重置输入框
            this.editUserDialogVisible = false
        },

        // 编辑用户提交
        editUserFormPost () {
            this.$refs.editUserForm.validate(async (valid) => {
                if (valid) {
                    // 提交编辑后的用户信息
                    const res = await modifyUserInfo(this.editUserForm)
                    if (res.hasOk) {
                        this.$message({
                            message: '用户信息修改成功',
                            type: 'success'
                        })
                    } else {
                        this.$message({
                            message: res.message,
                            type: 'error'
                        })
                    }
                    // 重置表格
                    this.getList()
                    this.editUserDialogVisible = false
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },

        // 头像上传成功执行
        handleAvatarSuccess (res, file) {
            if (res.hasOk) {
                this.avatarUrl = URL.createObjectURL(file.raw)
                console.log(this.avatarUrl)
                this.getList()
                this.$message.success('头像上传成功')
            } else {
                this.$message.error(res.message)
            }
        },
        // 头像上传前执行
        beforeAvatarUpload (file) {
            const isJPG = ['image/jpeg', 'image/png', 'image/jpg'].indexOf(file.type) !== -1
            const isLt2M = file.size / 1024 / 1024 < 2
            if (!isJPG) {
                return this.$message.error('上传头像图片只能是 JPG或 PNG 格式!')
            }
            if (!isLt2M) {
                return this.$message.error('上传头像图片大小不能超过 2MB!')
            }
            return isJPG && isLt2M
        },

        // 增加用户取消
        addUserFormCancel () {
            // 重置输入框
            this.addUserDialogVisible = false
            this.$refs.addUserForm.resetFields()
        },
        // 增加用户提交
        addUserFormPost () {
            this.$refs.addUserForm.validate(async (valid) => {
                if (valid) {
                    // 提交编辑后的用户信息
                    const res = await addUser(this.addUserForm)
                    if (res.hasOk) {
                        this.$message({
                            message: '用户信息修改成功',
                            type: 'success'
                        })
                        // 重置表格
                        this.getList()
                        this.$refs.addUserForm.resetFields()
                        this.addUserDialogVisible = false
                    } else {
                        this.$message({
                            message: res.message,
                            type: 'error'
                        })
                    }
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        sizeChange (limit) {
            this.limit = limit
            this.getList()
        },
        pageChange (offect) {
            this.offect = offect
            this.getList()
        },
        batchListEmit (batchList) {
            this.batchLoginList = batchList
            this.batchUploadListFlag = true
            this.isShowBatchTable = true
        },
        async batchLogin () {
            console.log(this.batchLoginList)
            const res = await batchRegister({
                batchLoginList: JSON.stringify(this.batchLoginList)
            })
            if (res.hasOk) {
                this.$message.success('批量注册成功')
                this.getList()
                this.batchUploadFlag = false
                this.batchUploadListFlag = false
                this.isShowBatchTable = false
            } else {
                this.$message.success('批量注册失败')
            }
        },
        batchLoginCancel () {
            this.batchUploadFlag = false
        }
    },
    created () {
        this.getList()
        this.getRoleList()
    },
}
</script>

<style lang="scss" scoped>
.loading {
    width: 100%;
    height: 100%;
}

.avatar-container {
    display: flex;
    justify-content: center;
}
::v-deep.avatar-uploader {
    margin-bottom: 20px;
}
::v-deep.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
::v-deep.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
::v-deep.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}
::v-deep.avatar {
    width: 100px;
    height: 100px;
    display: block;
}

.batch-contant {
    display: flex;
    justify-content: center;
}
</style>